/**
 * 
 */
package com.lanswon.qzsmk.util;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.model.CardNoGenerated;

/**
 * @author sun
 *
 */
public class FileUtil {
	
//	private static final String baseDir="D:\\Apache24\\htdocs\\qzsmk\\resource";
	
//	public static final String path = baseDir+"\\ExceptionData";

//	public static final String pp = baseDir+"\\makeCardFile";
	
//	public static final String responseFile = baseDir + "\\responseCardFile";;
	
//	public static final String responseFileSuccess = baseDir + "\\responseCardFileSuccess";
//	public static final String responseFileException = baseDir + "\\responseCardFileException";
	public static final String responseFileSuffix = ".txt";
	
	/**基础路径**/
//	public static final String DIR="http://127.0.0.1:9999/qzsmk";
//	public static final String DIR="http://192.168.0.12:9999/qzsmk";
	
//	public static final String FTPDIR="192.168.0.12";
	
	private static Logger logger = (Logger) LoggerFactory
			.getLogger(FileUtil.class);

	/**
	 * 记名制卡文件标题头
	 */
	public static final String[] str = { "证件种类", "证件号码", "姓名", "性别", "民族",
			"出生日期", "户籍地址", "手机号", "家庭地址", "邮政编码", "家长手机号", "所在学校", "所在班级",
			"3F00.0005.发卡方标识", "3F00.0005.区划代码", "3F00.0005.工程项目代码",
			"3F00.0005.卡主类型", "3F00.0005.卡子类型", "3F00.0005.市民卡卡号",
			"3F00.0005.市民卡校验码", "3F01.0015.发卡方标识", "3F01.0015.行政区划码",
			"3F01.0015.工程项目代码", "3F01.0015.户籍编码", "3F01.0015.应用类型标识",
			"3F01.0015.应用版本", "3F01.0015.应用序列号", "3F01.0015.卡类型",
			"3F01.0015.押金", "3F02.0015.发卡方标识", "3F02.0015.区划码",
			"3F02.0015.项目代码预留", "3F02.0015.应用类型标识", "3F02.0015.应用版本",
			"3F02.0015.应用序列号", "3F02.0015.卡类型", "3F02.0015.押金",
			"3F10.0015.应用状态标识", "3F10.0015.初始化版本", "3F10.0015.应用序列号",
			"3F10.0015.初始化启动日期", "9A00.0015.行业大类代码", "9A00.0015.单位编号",
			"9A00.0015.应用类型标识", "9A00.0015.应用版本", "9A00.0015.应用序列号",
			"9A00.0015.卡类型", "9A00.0016.单位员工编号", "9A00.0016.补充企业系统唯一码" };

	
	/**
	 * 不记名制卡文件标题头
	 */
	public static final String[] str1 = { "CARD_TASK_NO", "CARD_TYPE",
			"CITY_CODE", "START_NUMBER", "STOP_NUMBER", "RECORD_AMOUNT" };

	/**
	 * 开卡数据文件标题头
	 */
	public static final String[] str2 ={"证件种类","证件号码","姓名","性别","民族","出生日期","户籍地址","手机号","家庭地址","邮政编码","家长手机号","所在学校","市民卡卡号"};
	
	
	public static final String[] str3 = {"序号","市民卡号"};
	
	
	
	/**
	 * 物理路径下，将已上传的文件移到指定文件 D:\\resource\\unphotos ====> D:\resource\photosed
	 * 
	 * @param startPath
	 * @param endPath
	 */
	public static void moveTotherFolders(String startPath, String endPath) {
		logger.debug("原路径【{}】,目标路径【{}】",startPath,endPath);
		File startFile = new File(startPath);
		File tmpFile = new File(endPath);// 获取文件夹路径
		if (!tmpFile.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
			tmpFile.mkdirs();
		}
		File[] ff = tmpFile.listFiles();
		System.out.println(endPath);
		System.out.println(startFile.getName());
		File f = new File(endPath + File.separator + startFile.getName());
		for (File f1 : ff) {// 如果文件已经存在，先删除，在移动
			if (f1.getName().equalsIgnoreCase(startFile.getName())) {
				f1.delete();
			}
		}
		
		try {
			FileUtils.moveFileToDirectory(startFile, tmpFile, true);
		} catch (IOException e) {
			e.printStackTrace();
			logger.debug("移动文件失败，移动路径【{}】,目标路径【{}】",startFile.getAbsolutePath(),tmpFile.getAbsolutePath());
			String msg1="移动文件异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		}
	}	

	/**
	 * 生成路径
	 * @param basePath
	 * @param applyBatchNo
	 * @return
	 */
	public static String[] generatorPath(String root,String basePath, String applyBatchNo) {
		String p = basePath + File.separator + applyBatchNo +"_"+DateFormatUtils.format(new Date(), "yyyyMMddHHmm")+ ".xlsx";
		String gg =root.split("\\|")[0]+ p;
		File f = new File(gg);
		if (!f.getParentFile().exists()) {
			logger.info("正在创建目录。。。");
			f.getParentFile().mkdirs();
		}
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				String msg1="创建文件异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

			}
		}
		
		return new String[]{gg,root.split("\\|")[1]+ p};
	}
	
	/**
	 * 生成路径
	 * @param basePath
	 * @param applyBatchNo
	 * @return
	 */
	public static String generatorPath1(String basePath, String applyBatchNo) {
		String gg = PathContants.PROJECT_PATH_DOWNLOAD_APPLICATIONTEMPLATE+ File.separator + applyBatchNo + File.separator + applyBatchNo + ".xlsx";
		String g=basePath.split("\\|")[0]+File.separator+gg;
		File ff=new File(basePath.split("\\|")[0]+File.separator+PathContants.PROJECT_PATH_DOWNLOAD_APPLICATIONTEMPLATE);
		delDir(ff);
		File f = new File(g);
		if (!f.getParentFile().exists()) {
			logger.info("正在创建目录。。。");
			f.getParentFile().mkdirs();
		}
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				String msg1="创建文件异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

			}
		}
		return gg;
	}
	
	/**
	 * 内容上传至ftp
	 * @param filePath
	 * @param body
	 * @param title
	 * @return
	 */
	public static void contentToTxt_new(String filePath,String filename, String body,String[] title) {
		String content = cardTitle(title)+body;
		byte[] b = null;
		try {
			b = content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			String msg1="转码异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		}
		InputStream in = new  ByteArrayInputStream(b);  
		FtpUtil.uploadFile(PathContants.FTP_URL, PathContants.FTP_PORT, PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, filePath, filename, in);
		logger.info("FTP路径[{}],文件名[{}],上传成功",filePath,filename);
	}
	
	public static void main(String[] args) throws IOException {
//		contentToTxt_new("/crendentials/", "test.txt", "测试写文件", new String[]{"标题"});
//		moveTotherFolders("D:\\workspace\\qzsmk_card_lsw\\src\\main\\webapp\\uploadImages\\temp\\excel\\19_0_000095.xlsx",
//				"D:\\workspace\\qzsmk_card_lsw\\src\\main\\webapp\\uploadImages\\temp\\excel_imported");
	
//	FileUtils.moveDirectoryToDirectory(new File("D:\\workspace\\qzsmk_card_lsw\\src\\main\\webapp\\uploadImages\\temp\\img\\19_0_000095"), 
//			new File("D:\\workspace\\qzsmk_card_lsw\\src\\main\\webapp\\uploadImages\\temp\\img_imported"), true);
		System.out.println("CN1100".substring(2, 4));
		Integer aInteger=9999;
		Integer bInteger=9999;
		System.out.println(aInteger==bInteger);
	
	}

	/**
	 * 内容输出到指定文件
	 * @param filePath
	 * @param body
	 * @param title
	 * @return filePath 路径
	 */
	public static String contentToTxt(String filePath, String body,String[] title) {
		String ss = cardTitle(title);
		try {
			File f = new File(filePath);
			
			 if(!f.getParentFile().exists()){
	            	f.getParentFile().mkdirs();
	            }
	            
			if (f.exists()) {
				System.out.print("文件存在");
			} else {
				logger.debug("[{}]文件不存在", filePath);
				f.createNewFile();// 不存在则创建
			}

			
			BufferedWriter output = new BufferedWriter((new OutputStreamWriter(
					new FileOutputStream(f, true), "GBK")));
			PrintWriter out = new PrintWriter(output, true);
			out.println(ss+body);
			out.close();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
			String msg1="IO流异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		}
		return filePath;
	}
	
	/**
	 * 制卡文件表头
	 * @param title
	 * @return
	 */
	public static String cardTitle(String[] title) {
		StringBuffer sb = new StringBuffer();
		for (String s : title) {
			sb.append(s+"|");
		}
		sb.append("\r\n");
		return sb.toString();
	}
	
	 /** 
     * 根据需要创建文件夹 
     *  
     * @param dirPath 
     *            文件夹路径 
     * @param del 
     *            存在文件夹是否删除 
     */  
    public static void mkdir(String dirPath, boolean del) {  
        File dir = new File(dirPath);  
        if (dir.exists()) {  
            if (del)  
                dir.delete();  
            else  
                return;  
        }  
        if (!dir.getParentFile().exists()) {  
            dir.getParentFile().mkdirs();  
        }  
    }
    
    /**
     * 生成卡号文本
     */
    public static Boolean generatedCardNoText(List<String> list,String filename,String path){
    	StringBuffer sBuffer=new StringBuffer();
    	sBuffer.append("序号|市民卡号\r\n");
    	for(int i=0;i<list.size();i++){
    		if(i<list.size()-1){
    			sBuffer.append(i+1).append("|").append(list.get(i)+"\r\n");
    		}else if(i==(list.size()-1)){
    			sBuffer.append(i+1).append("|").append(list.get(i));
    		}
    		
    	}
    	int port=PathContants.FTP_PORT;
    	String username=PathContants.FTP_USERNAME;
    	String password=PathContants.FTP_PASSWORD;
    	 	
    	ByteArrayInputStream input=new ByteArrayInputStream(sBuffer.toString().getBytes());
    	Boolean f=FtpUtil.uploadFile(PathContants.FTP_URL, port, username, password, path, filename, input);
    	return f;
       
    }
    
    /**
     * 根据银行文件卡号段获取对应的文件名
     * @param startSegmentNo example "0010500==>10500"
     * @param endSegmentNo example "0025000==>25000"
     * @param cardNoGenerateds 
     * @return
     */
    public static List<String> getFileByCardNoSegment(int startSegmentNo,int endSegmentNo,List<CardNoGenerated> cardNoGenerateds ){
    	List<String> fileNames=new ArrayList<>();//对应卡号段的文件名
    	Iterator<CardNoGenerated> iterator=cardNoGenerateds.iterator();
    	while(iterator.hasNext()){
    		CardNoGenerated cardNoGenerated=iterator.next();
    		int currStartSegmentNo=Integer.valueOf(cardNoGenerated.getStartSegmentNo());
    		int currEndSegmentNo=Integer.valueOf(cardNoGenerated.getEndSegmentNo());
    		if(startSegmentNo>=currStartSegmentNo&&startSegmentNo<=currEndSegmentNo){
    			if(endSegmentNo<=currEndSegmentNo){
    				fileNames.add(cardNoGenerated.getFileName());
        			break;
    			}
    			if(endSegmentNo>currEndSegmentNo){
    				fileNames.add(cardNoGenerated.getFileName());
    				continue;
    			}	
    		}
    		if(startSegmentNo<currStartSegmentNo){
    			if(endSegmentNo>=currStartSegmentNo){
    				fileNames.add(cardNoGenerated.getFileName());
					continue;
    			}
//    			if(endSegmentNo>currEndSegmentNo){
//    				fileNames.add(cardNoGenerated.getFileName());
//    				continue;
//    			}
//    			if(endSegmentNo<=currEndSegmentNo){
//    				fileNames.add(cardNoGenerated.getFileName());
//    				continue;
//    			}
    			
    		}
    		
    	}
    	
    	return fileNames;
    }
    
    /**
     * 通过文件名获取卡号
     * @param fileNames
     * @return
     * @throws ApplicationException 
     */
    public static List<String> getCardNoByFileName(int startSegmentNo,int endSegmentNo,List<String> fileNames) throws ApplicationException{
    	List<String>list=new ArrayList<>();//存放卡号
    	Map<String, List<String>> map=new HashMap<>();
    	for(String fileName:fileNames){
    		String bankType=null;
    		if(fileName.substring(2, 4).equals("11")){
    			bankType="WF_BANK";
    		}if(fileName.substring(2, 4).equals("12")){
    			bankType="JS_BANK";
    		}
    		//String url="http://192.168.0.12:9999/qzsmk/resource/GeneratedCardNo/"+fileName;
    		//String url=PathContants.HTTP_ROOT+PathContants.FTP_PATH_GENERATEDCARDNO+File.separator+bankType+File.separator+"CN"+File.separator+fileName;
    		//InputStream in =HttpUtil.getInputStream(url);
    		String url=PathContants.FTP_PATH_GENERATEDCARDNO+bankType+PathContants.separator+"CN";
    		InputStream in=FtpUtil.getInputStream(PathContants.FTP_URL, PathContants.FTP_PORT, PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, url, fileName);
    		List<String>lists = HttpUtil.getStreamString(in);//文件内容
    		lists.remove(0);//去掉标题
    		map.put(fileName, lists);
    	}
    	Set<Map.Entry<String, List<String>>> set=map.entrySet();
    	Iterator<Map.Entry<String, List<String>>> iterator2=set.iterator();
    	while(iterator2.hasNext()){
    		Map.Entry<String, List<String>> entry=iterator2.next();
    		List<String> l=entry.getValue();
    		for(String str:l){
    			String currentNo= str.split("\\|")[1];
    			int com=Integer.valueOf(currentNo.substring(5));
    			if(com>=startSegmentNo&&com<=endSegmentNo){
    				list.add(currentNo);
    			}
    		}
    	}
    	return list;
    }
    
    
  
    /**
     * 删除
     * @param path
     */
    public static void delDir(File f) {
        // 判断是否是一个目录, 不是的话跳过, 直接删除; 如果是一个目录, 先将其内容清空.
        if(f.isDirectory()) {
            // 获取子文件/目录
            File[] subFiles = f.listFiles();
            // 遍历该目录
            for (File subFile : subFiles) {
                // 递归调用删除该文件: 如果这是一个空目录或文件, 一次递归就可删除. 如果这是一个非空目录, 多次
                // 递归清空其内容后再删除
                delDir(subFile);
            }
        }
        // 删除空目录或文件
        f.delete();
    }
}
